//
//  JMMyAnswerViewController.m
//  VoluntaryStar
//
//  Created by xiaorui on 15/9/7.
//  Copyright (c) 2015年 ios. All rights reserved.
//

#import "JMMyAnswerViewController.h"
#import "JMStudyCircleCell.h"
#import "JMAnswerCell.h"
#import "JMAppNetworkClient.h"
#import <UIImageView+WebCache.h>
#import "JMMyAnswerViewMode.h"
#import "JMAnswerMode.h"


@interface JMMyAnswerViewController ()<UITableViewDataSource,UITableViewDelegate>{

}

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArray;

@property (nonatomic, strong) UIView *bottomView;

@property (nonatomic, strong) UITextView *textView;

@property (nonatomic, strong) UIButton *senderBtn;
@end

@implementation JMMyAnswerViewController

- (UITableView *)tableView
{
    if (!_tableView) {
        UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, UI_SCREEN_WITH, UI_SCREEN_HEIGHT) style:UITableViewStyleGrouped];
        tableView.delegate = self;
        tableView.dataSource = self;
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        tableView.backgroundColor = [UIColor clearColor];
        tableView.backgroundView.backgroundColor = [UIColor clearColor];
        _tableView = tableView;
    }
    return _tableView;
}

- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc]initWithCapacity:0];
    }
    return _dataArray;
}

- (UIView *)bottomView
{
    if (!_bottomView) {
        _bottomView = [[UIView alloc]init];
        _bottomView.backgroundColor = UIColorFromRGB(0xf3f3f3);
    }
    return _bottomView;
}

- (UITextView *)textView
{
    if (!_textView) {
        _textView = [[UITextView alloc]init];
        _textView.backgroundColor = [UIColor whiteColor];
        _textView.layer.masksToBounds = YES;
        _textView.layer.borderWidth = 0.5;
        _textView.layer.borderColor = [UIColorFromRGB(0xc4c4c4) CGColor];

    }
    return _textView;
}

- (UIButton *)senderBtn
{
    if (!_senderBtn) {
        UIButton *button = [[UIButton alloc]init];
        [button setTitle:@"发送" forState:UIControlStateNormal];
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(senderButtonClick) forControlEvents:UIControlEventTouchUpInside];
        button.layer.masksToBounds = YES;
        button.layer.borderWidth = 0.5;
        button.layer.borderColor = [UIColorFromRGB(0xc4c4c4) CGColor];
        button.backgroundColor = [UIColor whiteColor];
        _senderBtn = button;
    }
    return _senderBtn;
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    self.navigationItem.title =@"回答";
    self.backBtn.hidden = YES;

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardShow:) name:UIKeyboardDidShowNotification  object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardHidden:) name:UIKeyboardDidHideNotification  object:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.tableView];
    self.bottomView.frame = CGRectMake(-0.5, UI_SCREEN_HEIGHT - 60, UI_SCREEN_WITH + 1, 61);
    self.bottomView.layer.masksToBounds =YES;
    self.bottomView.layer.borderWidth = 0.5;
    self.bottomView.layer.borderColor = [UIColorFromRGB(0x757575) CGColor];
    self.bottomView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.bottomView];
    
    self.textView.frame =CGRectMake(10, 5, UI_SCREEN_WITH - 70, self.bottomView.frameHeight - 10);
    self.textView.layer.borderColor = [UIColorFromRGB(0x757575) CGColor];
    [self.bottomView addSubview:self.textView];
    self.senderBtn.frame =CGRectMake(self.textView.frameRight + 5, self.textView.frameTop, 50, self.textView.frameHeight);
    [self.bottomView addSubview:self.senderBtn];
    [self getListAnswer];
}

#pragma mark  tableView delegate dasouce
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(section == 0){
        return 1;
    }
    return  self.dataArray.count;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section == 0){
        static NSString *str = @"IDD";
        JMStudyCircleCell * cell = [tableView dequeueReusableCellWithIdentifier:str];
        if(!cell){
            cell = [[JMStudyCircleCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:str];
            cell.countBnt.hidden =YES;
            cell.answerBnt.selected = NO;
            cell.selected =NO;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
       
        [cell.answerBnt setTitle:@"提问者" forState:UIControlStateNormal];
        [cell.answerBnt setImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
        [cell.iconImageView  sd_setImageWithURL:[NSURL URLWithString:self.mode.picString]];
        cell.nameLabel.text = self.mode.loginString;
        
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        NSTimeZone *timeZone = [NSTimeZone localTimeZone];
        [formatter setDateFormat : @"yyyy-MM-dd HH:mm:ss"];
        [formatter setTimeZone:timeZone];
        NSDate *dateTime = [formatter dateFromString:self.mode.timeString];
        NSDate *dateNow = [NSDate date];
        cell.timelabel.text = [NSString dateInterval:dateTime nowDate:dateNow];
        cell.typeLabel.text = [NSString stringWithFormat:@"%@%@",self.mode.gradeString,self.mode.subjectString];
        cell.typeLabel.textColor = self.mode.typeColor;
        cell.typeLabel.layer.borderColor = [self.mode.typeColor CGColor];
        
        [cell.infoImageView sd_setImageWithURL:[NSURL URLWithString:self.mode.logoString]];        return cell;
    }else{
        static NSString *str = @"IDE";
        JMAnswerCell * cell = [tableView dequeueReusableCellWithIdentifier:str];
        if(!cell){
            cell = [[JMAnswerCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:str];
            cell.selected =NO;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        
        cell.iconImageView.image = [UIImage imageNamed:@"projectImage.bundle/answer_image"];
        JMConfigure *cf = [JMConfigure sharedConfigureManger];
        cell.nameLabel.text = cf.user.nicheng;
        JMAnswerMode *mode = self.dataArray[indexPath.row];
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        NSTimeZone *timeZone = [NSTimeZone localTimeZone];
        [formatter setDateFormat : @"yyyy-MM-dd HH:mm:ss"];
        [formatter setTimeZone:timeZone];
        NSDate *dateTime = [formatter dateFromString:mode.ask_timeString];
        NSDate *dateNow = [NSDate date];
        cell.timeLabel.text = [NSString dateInterval:dateTime nowDate:dateNow];
        cell.textView.text = mode.ask_detailString;
        return cell;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section == 0){
      return   UI_SCREEN_WITH *0.546875;
    }else{
      return UI_SCREEN_WITH *0.3;
    }
}

-(void)senderButtonClick{
    JMConfigure *cf = [JMConfigure sharedConfigureManger];
    if(self.textView.text.length == 0){
        [JMTools showAlertView:self.view message:@"你没有做任何解答"];
        return;
    }
    if(cf.user){
        NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
        [dict setObject:cf.user.userId forKey:@"user"];
        [dict setObject:cf.user.token forKey:@"token"];
        [dict setObject:@"answer" forKey:@"act"];
        [dict setObject:[NSString stringWithFormat:@"%d",self.mode.questionId] forKey:@"qid"];
        [dict setObject:self.textView.text forKey:@"detail"];
        
        [JMAppNetworkClient circle_AnswerQuestionWithInfo:dict complete:^(id data, NSError *error) {
            if([data[@"status"] integerValue] == 1){
                JMAnswerMode *mode =[[JMAnswerMode alloc]init];
                
                NSDate *date = [NSDate date];
                NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
                NSTimeZone *timeZone = [NSTimeZone localTimeZone];
                [formatter setDateFormat : @"yyyy-MM-dd HH:mm:ss"];
                [formatter setTimeZone:timeZone];
                mode.ask_timeString = [formatter stringFromDate:date];
                mode.ask_detailString =self.textView.text;
                [self.dataArray addObject:mode];
                NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:1];
                [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
                [self.textView resignFirstResponder];
            }
        }];
    }
}

-(void)getListAnswer{

    JMConfigure *cf = [JMConfigure sharedConfigureManger];
    if(cf.user){
        NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
        [dict setObject:cf.user.userId forKey:@"user"];
        [dict setObject:cf.user.token forKey:@"token"];
        [dict setObject:@"sel" forKey:@"act"];
        [dict setObject:[NSString stringWithFormat:@"%d",self.mode.questionId ] forKey:@"qid"];
        
        [JMMyAnswerViewMode fetchMyAnswerQustionParametes:dict block:^(id data, NSError *error, id currData) {
            if([data[@"status"] integerValue] == 1){
                NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:1];
                self.dataArray = currData;
                [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
            }else{
            
            }
            [JMTools hiddenAlerView:self.view];
        }];
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 15;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}
#pragma mark -- jian pan huo dong
-(void)keyBoardShow:(NSNotification *)notion{
    NSDictionary *info = [notion userInfo];
    NSValue * value = info[UIKeyboardFrameEndUserInfoKey];
    CGFloat keyboardHeigh= [value CGRectValue].size.height;

    [UIView animateWithDuration:0.35 animations:^{
        self.bottomView.frame = CGRectMake(self.bottomView.frame.origin.x,UI_SCREEN_HEIGHT - keyboardHeigh - self.bottomView.frameHeight, self.bottomView.frame.size.width, self.bottomView.frame.size.height);
    } completion:^(BOOL finished) {
        
    }];
}

-(void)keyBoardHidden:(NSNotification *)notion{
//    NSDictionary *info = [notion userInfo];
//    NSValue * value = info[UIKeyboardFrameEndUserInfoKey];
//    CGFloat keyboardHeigh= [value CGRectValue].size.height;

    [UIView animateWithDuration:0.35 animations:^{
        self.bottomView.frame = CGRectMake(self.bottomView.frame.origin.x,UI_SCREEN_HEIGHT  - self.bottomView.frameHeight, self.bottomView.frame.size.width, self.bottomView.frame.size.height);
    } completion:^(BOOL finished) {
        
    }];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
